package com.supreme.securityserver.security;

import com.supreme.commonboot.exception.BizException;
import com.supreme.commonentity.mysql.primary.SysPermit;
import com.supreme.commonentity.mysql.primary.SysUser;
import com.supreme.commonmybatis.mapper.PermitMapper;
import com.supreme.commonmybatis.service.quick.UserOrmService;
import com.supreme.securityserver.utils.SecurityUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

@Service(value = "userAuthService")
public class UserAuthService implements UserDetailsService {

    @Resource
    private UserOrmService userOrmService;

    @Resource
    private PermitMapper permitMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = userOrmService.getUserByUsername(username);
        if (Objects.isNull(sysUser)) {
            throw new BizException("该用户不存在");
        }

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String rawPassword = authentication.getCredentials().toString();

        boolean matchesPassword = SecurityUtils.matchesPassword(rawPassword, sysUser.getPassword());
        if (!matchesPassword) {
            throw new BizException("密码不匹配");
        }

        return this.createLoginUser(sysUser);
    }

    private UserDetails createLoginUser(SysUser user) {
        Set<PermitAuthority> permissionSet = new HashSet<>();
        List<SysPermit> permitList = permitMapper.selectPermitByUserId(user.getUserId());
        permitList.forEach(sysPermit -> permissionSet.add(new PermitAuthority().setPermission(sysPermit.getPermitTag())));
        permissionSet.add(new PermitAuthority().setPermission("ROLE_supreme"));
        return new AuthUser(user, permissionSet);
    }
}
